<template>
  <div>
    <costList
      :calc-entry="calcEntryData"
      :is-show-go-edit="true"
      :game-info="gameInfo"
      @onEntryEdit="onPrevStep"
      @onReGetCharges="reGetCalcEntryOrder"
      @onGoEditEntry="goEditEntry"
    />

    <div class="bottom_btn_position summary_amount_position">
      <div v-if="!calcEntryData.isFree" class="summary_amount gl_clear" @click="clickShowSummaryAmount">
        <div class="gl_fl">费用详情</div>
        <div class="gl_fr">
          <van-icon name="arrow" />
        </div>
      </div>
      <van-row>
        <van-col :span="16">
          <div v-if="!calcEntryData.isFree" class="total_amount">
            <span>合计：</span>
            <span class="gl_ft_weight">{{ formatMoney(calcEntryData.totalAmount - calcEntryData.paidAmount) }} 元</span>
          </div>
        </van-col>
        <van-col :span="8">
          <template v-if="!calcEntryData.isFree">
            <van-button :loading="payBtnDisable || !hasPayWayInCalcEntry" type="info" block @click="clickPay()">去支付</van-button>
          </template>
          <template v-else>
            <van-button :loading="payBtnDisable" type="info" block @click="clickComplate()">完成</van-button>
          </template>
        </van-col>
      </van-row>
    </div>

    <!-- 详细费用弹出层 -->
    <van-overlay class="van_overlay_summary" :show="showSummaryAmount" @click="showSummaryAmount = false" />
    <van-popup v-model="showSummaryAmount" position="bottom" :overlay="false" class="van_popup_summary">
      <ul class="summary_popup">
        <li v-for="(item, index) in calcEntryData.summary" :key="index" class="summary_item gl_clear">
          <span class="gl_fl">{{ item.chargeTypeName }}</span>
          <span class="gl_fr">{{ formatMoney(item.amount) }} 元</span>
        </li>
        <li class="summary_item summary_total gl_clear">
          <span class="gl_fl">已缴纳费用</span>
          <span class="gl_fr">{{ formatMoney(calcEntryData.paidAmount) }} 元</span>
        </li>
      </ul>
    </van-popup>

    <!-- 支付方式弹出层 -->
    <van-popup v-model="dialogVisibleForPay" class="pay_type" :overlay="false">
      <div class="pay_type_list">
        <div class="pay_type_item pay_type_offline gl_clear" @click="clickPayOffline()">线下支付</div>
        <div class="pay_type_item pay_type_online gl_clear" @click="clickPayOnline()">线上支付</div>
      </div>
      <div v-if="modalPayLoding" class="page_loading fixed" style="background: rgba(255, 255, 255, 0.4);">
        <van-loading size="24px" vertical color="#fff">加载中...</van-loading>
      </div>
    </van-popup>
    <van-overlay class="van_overlay_pay" :show="dialogVisibleForPay" @click="dialogVisibleForPay = false" />

    <!-- 提交表单 -->
    <form id="form" ref="form" action="https://unipay.ydfuture.com/api/v1/trade/cashDesk" method="post" style="display:none">
      <input ref="pay_params" type="text" name="pay_params" value="">
      <button type="submit">提交</button>
    </form>

    <!-- 支付方式弹出层 -->
    <van-popup v-model="offlineDialogVisible" class="pay_type" style="width:90%" :overlay="false">
      <offline-pay-info :offline-data="offlineData" @onJumpToOrderCenter="jumpToOrderCenter" />
    </van-popup>
    <van-overlay class="van_overlay_pay" :show="offlineDialogVisible" @click="offlineDialogVisible = false" />
  </div>
</template>

<script>
import CostList from '@/viewMobile/components/CostList';
import OfflinePayInfo from '@/viewMobile/components/OfflinePayInfo';

import {
  api_POST_EventsManagementEntryOrderCalculateEntryOrder, // EntryOrder 计算费用
  api_POST_EventsManagementEntryOrderSubmitOrder
} from '@/extend/api/gameswaggerApi/app';

import {
  api_GET_TradePersonalOrderCollectionCode, // 获取线下支付订单的收款码信息
  api_GET_TradePayOrderParameter // 获取支付订单的参数
} from '@/extend/api/swaggerApi/app';

import {
  Api_GET_TradePayOrderParameterQO
} from '@/lib/form/swaggerForm';

export default {
  components: {
    CostList,
    OfflinePayInfo
  },
  props: {
    currentUserType: {
      type: String,
      default: ''
    },
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    },
    isShow: {
      type: Boolean,
      default: false
    },
    gameTenantId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      orderParameterQO: new Api_GET_TradePayOrderParameterQO(),
      dialogVisibleForPay: false,
      orderNo: '', // 订单编号
      isOnlinePayment: true, // 是否是线上支付
      calcEntryData: {},
      payBtnDisable: true,
      calcEntryLoading: true,
      modalPayLoding: false,
      showSummaryAmount: false,
      offlineDialogVisible: false,
      offlineData: {}
    };
  },
  computed: {
    isFreeGame() {
      return this.gameInfo.setting.isFree;
    },
    hasPayWayInCalcEntry () {
      const _setOnline = this.calcEntryData.isSetOnline; // 设置了线上支付
      const _setOffline = this.calcEntryData.isSetOffline; // 设置了线下支付
      return _setOnline || _setOffline;
    }
  },
  watch: {
    isShow: {
      immediate: true,
      handler(val) {
        if (val) {
          this.calcEntryLoading = true;
          this.getCalcEntryOrder();
        }
      }
    }
  },
  methods: {
    // 点击上一步
    onPrevStep() {
      this.$emit('onPrevStep');
    },
    // 重新获取信息
    reGetCalcEntryOrder() {
      this.getCalcEntryOrder();
    },
    // 校验赛事是否收费，选择是否计算费用
    getCalcEntryOrder() {
      const _vo = {
        competitionId: this.gameInfo.id
      };
      if (this.currentUserType === 'Personal') {
        _vo.registerId = this.requiredIdData.registerId;
      }
      if (this.currentUserType === 'Delegation') {
        _vo.delegationId = this.requiredIdData.delegationId;
      }
      this.calcEntryOrderApi(_vo);
    },
    // 计算订单费用API
    calcEntryOrderApi (vo) {
      this.payBtnDisable = true;
      api_POST_EventsManagementEntryOrderCalculateEntryOrder(vo)
        .then(
          res => {
            this.payBtnDisable = false;
            this.calcEntryLoading = false;
            this.calcEntryData = res;
          }
        )
        .catch(
          error => {
            this.calcEntryData = {}; // 清空数据
            this.calcEntryLoading = false;
            this.$toast.fail(`费用获取失败 ${error.error.message}`);
          }
        );
    },
    // 格式化货币格式 （分）
    formatMoney(num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    // 点击支付按钮
    clickPay () {
      const _checkResult = this.checkFootCover();
      if (_checkResult) {
        this.judgeIsShowDialogVisibleForPay();
      } else {
        this.$toast.fail(`脚码信息不完整，请在费用明细中核实脚码信息`);
      }
    },
    // 判断是否显示支付方式选择弹窗
    judgeIsShowDialogVisibleForPay () {
      // 请注意代码顺序不可调整
      const _setOnline = this.calcEntryData.isSetOnline; // 设置了线上支付
      const _setOffline = this.calcEntryData.isSetOffline; // 设置了线下支付

      // 当同时设置了线上与线下支付时，弹窗让用户选择支付方式
      if (_setOnline && _setOffline) {
        this.dialogVisibleForPay = true;
        return;
      }

      // 仅设置了线上支付
      if (_setOnline) {
        this.clickPayOnline();
        return;
      }

      // 仅设置了线下支付
      if (_setOffline) {
        this.clickPayOffline();
        return;
      }
    },
    // 校验脚码信息是否完整
    checkFootCover () {
      const charges = this.calcEntryData.charges;
      if (charges.length) {
        const _footData = charges.find(item => item.code === 'Foot');
        if (_footData) {
          for (let i = 0; i < _footData.items.length; i++) {
            const item = _footData.items[i];
            if (item.needFootCover && !item.footSize) {
              return false;
            }
          }
        }
      }
      return true;
    },
    // 点击完成
    clickComplate () {
      const _checkResult = this.checkFootCover();
      if (_checkResult) {
        this.isOnlinePayment = true;
        this.submitOrder();
      } else {
        this.$toast.fail(`脚码信息不完整，请在费用明细中核实脚码信息`);
      }
    },
    // 线上支付
    clickPayOnline () {
      this.isOnlinePayment = true;
      this.submitOrder();
    },
    // 线下支付
    clickPayOffline () {
      this.isOnlinePayment = false;
      this.submitOrder();
    },
    clickShowSummaryAmount () {
      this.showSummaryAmount = !this.showSummaryAmount;
    },
    // 提交订单
    submitOrder() {
      this.modalPayLoding = true;
      const _vo = {
        competitionId: this.gameInfo.id,
        isOnlinePayment: this.isOnlinePayment
      };

      if (this.currentUserType === 'Personal') {
        _vo.registerId = this.requiredIdData.registerId;
      }
      if (this.currentUserType === 'Delegation') {
        _vo.delegationId = this.requiredIdData.delegationId;
      }

      api_POST_EventsManagementEntryOrderSubmitOrder(_vo)
        .then(
          res => {
            if (this.isFreeGame) {
              // 免费赛事跳转至报项中心
              const gameTenantId = this.gameTenantId ? '_' + this.gameTenantId : '';
              this.$router.push({
                path: `/myCenter/${this.gameInfo.route}${gameTenantId}/entry`
              });
            } else {
              if (this.isOnlinePayment) {
                // 如果是线上支付
                this.payment(res.orderNo);
              } else {
                // 线下支付，展示获取订单信息，展示收款账户信息
                this.getOrderDetails(res.orderNo);
              }
            }
          }
        )
        .catch(
          error => {
            this.$toast.fail(`订单创建失败 ${error.error.message}`);
            console.log(error);
            this.modalPayLoding = false;
          }
        );
    },
    // 去支付
    payment(orderNo) {
      if (orderNo) {
        const _origin = window.location.origin;
        const _pathname = window.location.pathname;
        const _orderUrl = '#/myCenter/order';
        const url = _origin + _pathname + _orderUrl;
        this.orderParameterQO.OrderNo = orderNo;
        this.orderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(this.orderParameterQO)
          .then(res => {
            this.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
            this.$refs.form.submit();
          });
      }
    },
    // 获取订单详情，用于线下支付展示收款账户信息
    getOrderDetails (orderNo) {
      api_GET_TradePersonalOrderCollectionCode({ orderNo: orderNo })
        .then(
          res => {
            console.log('getOrderDetails -> res', res);
            res._orderNo = orderNo;
            this.offlineData = res;
            this.offlineDialogVisible = true;
            this.dialogVisibleForPay = false;
          }
        )
        .catch(
          error => {
            this.$toast.fail(`保险费已支付，请支付报名费`);
            console.log('getOrderDetails -> error', error);
          }
        );
    },
    // 跳转到订单中心
    jumpToOrderCenter () {
      // 线下支付,直接去订单中心
      const gameTenantId = this.gameTenantId ? '_' + this.gameTenantId : '';
      this.$router.push({
        path: `/myCenter/${this.gameInfo.route}${gameTenantId}/order`
      });
    },
    goEditEntry () {
      this.$emit('onPrevStep');
    }
  }
};
</script>

<style scoped>
.total_amount {
  font-size: 12px;
  font-weight: 400;
  text-align: left;
  color: #333333;
  line-height: 44px;
}
.van_popup_summary {
  min-height: 30%;
  bottom: 84px;
}
.van_overlay_summary {
  top: -84px;
}
.van_overlay_pay {
  z-index: 3010;
}
.summary_amount {
  box-sizing: border-box;
  padding: 0 10px;
  position: absolute;
  width: 100%;
  top: -30px;
  left: 0;
  height: 30px;
  line-height: 30px;
  font-size: 12px;
  color: #333333;
  background-color: #fff;
  border-top: 1px solid #f1f1f1;
}
.summary_amount_position {
  z-index: 3000;
}
.summary_amount_position.bottom_btn_position {
  z-index: 3000;
}

.summary_popup {
  padding: 15px 20px;
}
.summary_item.summary_total {
  /* padding: 5px 0; */
  font-weight: bold;
}
.summary_item {
  font-size: 14px;
  line-height: 24px;
}

.pay_type.van-popup {
  background-color: transparent;
  z-index: 3015 !important; /* 覆盖组件原有层级，避免与summary弹层冲突 */
}
.pay_type_list {
  position: relative;
  display: flex;
  justify-content: space-around;
  flex-direction: column;
}
.pay_type_item {
  width: 260px;
  height: 84px;
  padding: 0 50px;
  margin-bottom: 12px;
  text-align: right;
  color: #fff;
  font-size: 24px;
  line-height: 84px;
  cursor: pointer;
}
.pay_type_item:last-child {
  margin-bottom: 0;
}
.pay_type_online {
  background-image: url('../../../assets/images/pay/online.png');
  background-repeat: no-repeat;
}
.pay_type_offline {
  background-image: url('../../../assets/images/pay/offline.png');
  background-repeat: no-repeat;
}
</style>
